/*******************************************************************************
 * Copyright (c) 2011 EclipseDevX.org and others.
 * 
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at:
 * 
 *     http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

package org.eclipsedevx.core.usage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipsedevx.core.DevXCorePlugin;
import org.osgi.framework.Version;

public class UsageStatsJob extends Job {
	private final static String BASE_URL = "http://eclipsedevx.appspot.com/usage";
	//private final static String BASE_URL = "http://localhost:8888/usage";

	private static final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;

	public UsageStatsJob() {
		super("Eclipse DevX Usage Statistics");

		setSystem(true);
	}

	@Override
	protected IStatus run(IProgressMonitor monitor) {
		Map<String, String> stats = collectStats();

		pingUrl(stats);

		schedule(MILLIS_PER_DAY);

		return Status.OK_STATUS;
	}

	private Map<String, String> collectStats() {
		Map<String, String> stats = new HashMap<String, String>();

		stats.put("eclipse.version", getEclipseVersion());
		stats.put("os.name", System.getProperty("os.name"));
		stats.put("os.version", System.getProperty("os.version"));
		stats.put("devx.version", getDevXVersion());
		stats.put("user.language", System.getProperty("user.language"));
		stats.put("user.country", System.getProperty("user.country"));

		return stats;
	}

	private String getEclipseVersion() {
		return getVersionText(ResourcesPlugin.getPlugin().getBundle().getVersion());
	}

	private String getDevXVersion() {
		return getVersionText(DevXCorePlugin.getPlugin().getBundle().getVersion());
	}

	private static String getVersionText(Version version) {
		return version.getMajor() + "." + version.getMinor() + "." + version.getMicro();
	}

	@SuppressWarnings("unused")
	private void pingUrl(Map<String, String> stats) {
		try {
			URL url = new URL(BASE_URL);

			HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

			urlConnection.addRequestProperty("User-Agent", "DevX");
			urlConnection.addRequestProperty("DevX-machine.id", DevXCorePlugin.getPlugin().getMachineId());

			for (String key : stats.keySet()) {
				String value = stats.get(key);
				
				if (value == null) {
					continue;
				}
				
				value = URLEncoder.encode(value, "UTF-8");
				
				urlConnection.addRequestProperty("DevX-" + key, value);
			}

			InputStream in = urlConnection.getInputStream();

			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];

			int count = in.read(buffer);

			while (count > 0) {
				bout.write(buffer, 0, count);
				count = in.read(buffer);
			}

			int responseCode = urlConnection.getResponseCode();
			String responseMessage = urlConnection.getResponseMessage();
			String responseData = new String(bout.toByteArray());
			
			in.close();
		} catch (MalformedURLException e) {
			DevXCorePlugin.logError(e);
		} catch (IOException e) {
			// ignore
		}
	}

}
